#include <iostream>
#include <string>
#include <chrono>
#include "viml/compiler.h"
#include "viml/vm.h"
#include "viml/parser.h"
#include "viml/ast.h"

using namespace viml;

void print_header(const std::string& title) {
    std::cout << "\n" << std::string(60, '=') << std::endl;
    std::cout << " " << title << std::endl;
    std::cout << std::string(60, '=') << std::endl;
}

// 测试函数性能
struct PerformanceResult {
    double execution_time_ms;
    size_t function_calls;
    MemoizationCache::Statistics cache_stats;
};

PerformanceResult measure_performance(const std::string& source, VM& vm, 
                                    const std::string& test_name = "test") {
    auto start_time = std::chrono::high_resolution_clock::now();
    
    // 重置统计信息
    vm.reset_statistics();
    vm.clear_memoization_cache();
    
    // 编译并执行代码
    Compiler compiler;
    auto bytecode = compiler.compile(source, test_name);
    Value result = vm.execute(bytecode);
    
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
    
    PerformanceResult metrics;
    metrics.execution_time_ms = duration.count() / 1000.0;
    metrics.function_calls = vm.get_statistics().function_calls;
    metrics.cache_stats = vm.get_memoization_statistics();
    
    return metrics;
}

int main() {
    try {
        Compiler compiler;
        VM vm;
        
        print_header("RecTest函数纯度分析与记忆化测试");
        
        // 读取RecTest函数
        std::string rectest_source = R"(
function RecTest(n)
  if n < 3
    return n
  else
    return RecTest(n-1) + RecTest(n-2) + RecTest(n-3)
  endif
endfunction
        )";
        
        std::cout << "RecTest函数定义：" << std::endl;
        std::cout << rectest_source << std::endl;
        
        // 1. 函数纯度分析
        print_header("步骤1：自动函数纯度分析");
        
        Parser parser(rectest_source);
        auto program = parser.parse();
        
        // 查找RecTest函数并分析其纯度
        for (auto& stmt : program->statements) {
            if (auto func_stmt = dynamic_cast<FunctionStatement*>(stmt.get())) {
                if (func_stmt->name == "RecTest") {
                    std::cout << "分析函数: " << func_stmt->name << std::endl;
                    
                    auto analysis_result = vm.analyze_and_add_function(*func_stmt);
                    
                    std::cout << "分析结果：" << std::endl;
                    std::cout << "  是否为纯函数: " << (analysis_result.is_pure ? "是" : "否") << std::endl;
                    std::cout << "  是否有副作用: " << (analysis_result.has_side_effects ? "是" : "否") << std::endl;
                    std::cout << "  是否依赖外部状态: " << (analysis_result.has_external_dependency ? "是" : "否") << std::endl;
                    
                    if (!analysis_result.function_calls.empty()) {
                        std::cout << "  调用的函数: ";
                        for (size_t i = 0; i < analysis_result.function_calls.size(); ++i) {
                            if (i > 0) std::cout << ", ";
                            std::cout << analysis_result.function_calls[i];
                        }
                        std::cout << std::endl;
                    }
                    
                    if (!analysis_result.reason.empty()) {
                        std::cout << "  说明: " << analysis_result.reason << std::endl;
                    }
                    
                    if (analysis_result.is_pure) {
                        std::cout << "  ✓ RecTest函数已自动添加到记忆化白名单" << std::endl;
                    } else {
                        std::cout << "  ✗ RecTest函数未添加到记忆化白名单" << std::endl;
                    }
                }
            }
        }
        
        // 2. 无记忆化性能测试
        print_header("步骤2：无记忆化性能基准测试");
        
        vm.set_memoization_enabled(false);
        
        std::string test_source_small = rectest_source + "\nlet result = RecTest(15)\n";
        std::string test_source_medium = rectest_source + "\nlet result = RecTest(18)\n";
        
        std::cout << "测试RecTest(15) - 无记忆化：" << std::endl;
        auto no_memo_small = measure_performance(test_source_small, vm, "RecTest(15)_NoMemo");
        std::cout << "  执行时间: " << no_memo_small.execution_time_ms << "ms" << std::endl;
        std::cout << "  函数调用: " << no_memo_small.function_calls << " 次" << std::endl;
        std::cout << "  结果: " << vm.get_global("result").as_number() << std::endl;
        
        std::cout << "\n测试RecTest(18) - 无记忆化：" << std::endl;
        auto no_memo_medium = measure_performance(test_source_medium, vm, "RecTest(18)_NoMemo");
        std::cout << "  执行时间: " << no_memo_medium.execution_time_ms << "ms" << std::endl;
        std::cout << "  函数调用: " << no_memo_medium.function_calls << " 次" << std::endl;
        std::cout << "  结果: " << vm.get_global("result").as_number() << std::endl;
        
        // 3. 记忆化性能测试
        print_header("步骤3：记忆化性能优化测试");
        
        vm.set_memoization_enabled(true);
        vm.optimize_memoization_for_recursive_algorithms();
        
        std::cout << "测试RecTest(15) - 有记忆化：" << std::endl;
        auto memo_small = measure_performance(test_source_small, vm, "RecTest(15)_WithMemo");
        std::cout << "  执行时间: " << memo_small.execution_time_ms << "ms" << std::endl;
        std::cout << "  函数调用: " << memo_small.function_calls << " 次" << std::endl;
        std::cout << "  缓存命中: " << memo_small.cache_stats.hits << " 次" << std::endl;
        std::cout << "  缓存未命中: " << memo_small.cache_stats.misses << " 次" << std::endl;
        std::cout << "  命中率: " << memo_small.cache_stats.hit_rate << "%" << std::endl;
        std::cout << "  结果: " << vm.get_global("result").as_number() << std::endl;
        
        std::cout << "\n测试RecTest(18) - 有记忆化：" << std::endl;
        auto memo_medium = measure_performance(test_source_medium, vm, "RecTest(18)_WithMemo");
        std::cout << "  执行时间: " << memo_medium.execution_time_ms << "ms" << std::endl;
        std::cout << "  函数调用: " << memo_medium.function_calls << " 次" << std::endl;
        std::cout << "  缓存命中: " << memo_medium.cache_stats.hits << " 次" << std::endl;
        std::cout << "  缓存未命中: " << memo_medium.cache_stats.misses << " 次" << std::endl;
        std::cout << "  命中率: " << memo_medium.cache_stats.hit_rate << "%" << std::endl;
        std::cout << "  结果: " << vm.get_global("result").as_number() << std::endl;
        
        // 4. 更大规模测试 (如果记忆化有效)
        if (memo_small.cache_stats.hits > 0) {
            print_header("步骤4：大规模记忆化效果验证");
            
            std::string test_source_large = rectest_source + "\nlet result = RecTest(20)\n";
            
            std::cout << "测试RecTest(20) - 有记忆化：" << std::endl;
            auto memo_large = measure_performance(test_source_large, vm, "RecTest(20)_WithMemo");
            std::cout << "  执行时间: " << memo_large.execution_time_ms << "ms" << std::endl;
            std::cout << "  函数调用: " << memo_large.function_calls << " 次" << std::endl;
            std::cout << "  缓存命中: " << memo_large.cache_stats.hits << " 次" << std::endl;
            std::cout << "  缓存未命中: " << memo_large.cache_stats.misses << " 次" << std::endl;
            std::cout << "  命中率: " << memo_large.cache_stats.hit_rate << "%" << std::endl;
            std::cout << "  结果: " << vm.get_global("result").as_number() << std::endl;
        }
        
        // 5. 性能对比总结
        print_header("步骤5：性能提升总结");
        
        if (memo_small.cache_stats.hits > 0) {
            double speedup_small = no_memo_small.execution_time_ms / memo_small.execution_time_ms;
            double speedup_medium = no_memo_medium.execution_time_ms / memo_medium.execution_time_ms;
            
            std::cout << "RecTest(15) 性能提升：" << std::endl;
            std::cout << "  时间提升: " << speedup_small << "倍" << std::endl;
            std::cout << "  函数调用减少: " << (1.0 - (double)memo_small.function_calls / no_memo_small.function_calls) * 100.0 << "%" << std::endl;
            
            std::cout << "\nRecTest(18) 性能提升：" << std::endl;
            std::cout << "  时间提升: " << speedup_medium << "倍" << std::endl;
            std::cout << "  函数调用减少: " << (1.0 - (double)memo_medium.function_calls / no_memo_medium.function_calls) * 100.0 << "%" << std::endl;
            
            std::cout << "\n✅ RecTest函数成功实现记忆化优化！" << std::endl;
        } else {
            std::cout << "❌ RecTest函数未能实现记忆化优化" << std::endl;
        }
        
        print_header("总结");
        std::cout << "RecTest函数特点分析：" << std::endl;
        std::cout << "1. 这是一个三项递归函数（类似三数斐波那契）" << std::endl;
        std::cout << "2. 递归公式: RecTest(n) = RecTest(n-1) + RecTest(n-2) + RecTest(n-3)" << std::endl;
        std::cout << "3. 基础情况: n < 3 时返回 n" << std::endl;
        std::cout << "4. 时间复杂度: 无记忆化时约为 O(3^n)，有记忆化时为 O(n)" << std::endl;
        std::cout << "5. 记忆化效果: 由于大量重复子问题，记忆化效果显著" << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "测试出错: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}